//
//  ZBGravityAnimationView.m
//  送礼
//
//  Created by 华惠友 on 2017/9/19.
//  Copyright © 2017年 华惠友. All rights reserved.
//

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#import "ZBGravityAnimationView.h"

@interface ZBGravityAnimationView ()
//现实动画
@property(nonatomic ,strong)UIDynamicAnimator * dynamicAnimator;
//现实行为
@property(nonatomic ,strong)UIDynamicItemBehavior * dynamicItemBehavior;
//重力行为
@property(nonatomic ,strong)UIGravityBehavior * gravityBehavior;
//碰撞行为
@property(nonatomic ,strong)UICollisionBehavior * collisionBehavior;

@property (nonatomic, copy) AnimationFinishBlock finishedBlock;

@end

@implementation ZBGravityAnimationView


- (instancetype)init{
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    return self;
}

//重力
- (void)animationWithGravity:(AnimationFinishBlock)finished{
    self.finishedBlock = finished;
    
    if (!self.dynamicAnimator) {
        //现实动画
        self.dynamicAnimator = [[UIDynamicAnimator alloc]initWithReferenceView:self];
        //现实行为
        self.dynamicItemBehavior = [[UIDynamicItemBehavior alloc]init];
        //弹力值
        self.dynamicItemBehavior.elasticity = 0.3;
        //允许旋转
        self.dynamicItemBehavior.allowsRotation = YES;
        
        //重力行为
        self.gravityBehavior = [[UIGravityBehavior alloc]init];
        
        //碰撞行为
        self.collisionBehavior = [[UICollisionBehavior alloc]init];
        //开启刚体碰撞
        self.collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
        
        //将行为添加到现实动画中
        [self.dynamicAnimator addBehavior:self.dynamicItemBehavior];
        [self.dynamicAnimator addBehavior:self.gravityBehavior];
        [self.dynamicAnimator addBehavior:self.collisionBehavior];
    }
    int x = arc4random() % (int)[UIScreen mainScreen].bounds.size.width;
    int size = arc4random() % 50 + 30;
    
    NSArray * imageArray = @[@"bear0@2x",@"bear1@2x",@"bear2@2x",@"heart0",@"heart1",@"heart2",@"heart3",@"heart4",@"heart5"];
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, 0, size, size)];
    imageView.image = [UIImage imageNamed:imageArray[arc4random() % imageArray.count]];
    [self addSubview:imageView];
    
    //遵循行为
    [self.dynamicItemBehavior addItem:imageView];
    [self.gravityBehavior addItem:imageView];
    [self.collisionBehavior addItem:imageView];
    
    [self performSelector:@selector(deleteImage:) withObject:imageView afterDelay:2];
}

//消除行为且删除
- (void)deleteImage:(id)object{
    UIImageView *imagView = (UIImageView *)object;
    [self.dynamicItemBehavior removeItem:imagView];
    [self.gravityBehavior removeItem:imagView];
    [self.collisionBehavior removeItem:imagView];
    [imagView removeFromSuperview];
    
    [self removeFromSuperview];
    self.finishedBlock();
}


@end
